package com.zc.angelica.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zc.angelica.entity.Account;
import com.zc.angelica.entity.ButtonInfo;
import com.zc.angelica.entity.ResponseData;
import com.zc.angelica.mapper.MenuInfoMapper;
import com.zc.angelica.entity.MenuInfo;
import com.zc.angelica.service.MenuInfoService;
import com.zc.angelica.utils.SecurityUtil;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 菜单信息表(MenuInfo)表服务实现类
 *
 * @author makejava
 * @since 2022-04-05 23:52:04
 */
@Service
public class MenuInfoServiceImpl extends ServiceImpl<MenuInfoMapper, MenuInfo> implements MenuInfoService {

    //TODO 新增缓存

    @Override
    public ResponseData addMenu(MenuInfo menuInfo) {
        int sort = 0;
        if (menuInfo.getParentId() == null) {
            menuInfo.setParentId(0L);
        }
        if (menuInfo.getPlatformCode() == null || menuInfo.getPlatformCode().equals("")) {
            return ResponseData.error("平台code不能为空");
        }
        if (menuInfo.getMenuCode() == null || menuInfo.getMenuCode().equals("")) {
            return ResponseData.error("菜单code不能为空");
        }
        QueryWrapper<MenuInfo> menuWrapper = new QueryWrapper<>();
        menuWrapper.eq("menu_code", menuInfo.getMenuCode());
        long codeCount = this.count(menuWrapper);
        if (codeCount > 0) {
            return ResponseData.error("菜单code不可以重复");
        }
        MenuInfo menuBySort = this.baseMapper.getMenuMaxSort(menuInfo.getParentId());
        if (menuBySort != null && menuBySort.getMenuSort() != null) {
            sort = menuBySort.getMenuSort() + 1;
        }
        menuInfo.setMenuSort(sort);
        this.save(menuInfo);
        return ResponseData.success("添加成功");
    }

    //TODO 查询构建树
    @Override
    public ResponseData getMenuByPage(Integer pageNo, Integer pageSize) {
        Account accountInfo = SecurityUtil.getAccountInfo();
        if (accountInfo != null) {
            IPage<MenuInfo> page = new Page<>(pageNo, pageSize);
            if (SecurityUtil.getAccountInfo().getAuthorities().size() > 0) {
                List<String> roleCode = accountInfo.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
                IPage<MenuInfo> menuByPage = this.baseMapper.getMenuByPage(page, roleCode, accountInfo.getId());
                return ResponseData.success(menuByPage);
            }
            return ResponseData.error("没有查询到角色信息！");
        }
        return ResponseData.error("没有查询到用户信息，请重新登录再试");
    }

    //TODO 查询构建树
    @Override
    public ResponseData getAllMenu() {
        Account accountInfo = SecurityUtil.getAccountInfo();
        if (accountInfo != null) {
            if (accountInfo.getAuthorities()!=null&&accountInfo.getAuthorities().size() > 0) {
                List<String> roleCode = SecurityUtil.getAccountInfo().getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
                List<MenuInfo> menuByPage = this.baseMapper.getAllMenu(roleCode, accountInfo.getId());

                List<TreeNode<Object>> nodeList = CollUtil.newArrayList();

                for (MenuInfo menu : menuByPage) {
                    
                    Map<String, Object> map = new HashMap<>();
                    map.put("menuCode",menu.getMenuCode());
                    map.put("menuType",menu.getMenuType());
                    map.put("menuUrl",menu.getMenuUrl());
                    map.put("manuIcon",menu.getManuIcon());
                    map.put("parentCode",menu.getParentCode());
                    map.put("platformCode",menu.getPlatformCode());
                    TreeNode<Object> node = new TreeNode<>()
                            .setId(menu.getId())
                            .setParentId(menu.getParentId())
                            .setName(menu.getMenuName())
                            .setWeight(menu.getMenuSort())
                            .setExtra(map);
                    nodeList.add(node);
                }
                TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
                List<Tree<Object>> treeNodes = TreeUtil.build(nodeList, 0L, treeNodeConfig,
                        (treeNode, tree) -> {
                            tree.setId(treeNode.getId());
                            tree.setParentId(treeNode.getParentId());
                            tree.setWeight(treeNode.getWeight());
                            tree.setName(treeNode.getName());
                            // 扩展属性 ...
                            tree.putExtra("menuCode", treeNode.getExtra().getOrDefault("menuCode", null));
                            tree.putExtra("menuType", treeNode.getExtra().getOrDefault("menuType", null));
                            tree.putExtra("menuUrl", treeNode.getExtra().getOrDefault("menuUrl", null));
                            tree.putExtra("manuIcon", treeNode.getExtra().getOrDefault("manuIcon", null));
                            tree.putExtra("parentCode", treeNode.getExtra().getOrDefault("parentCode", null));
                            tree.putExtra("platformCode", treeNode.getExtra().getOrDefault("platformCode", null));
                        });

                return ResponseData.success(treeNodes);
            }
            return ResponseData.error("没有查询到角色信息！");
        }
        return ResponseData.error("没有查询到用户信息，请重新登录再试");
    }

    @Override
    public ResponseData delMenu(Long id) {
        boolean delete = this.removeById(id);
        if (delete) {
            return ResponseData.success("删除成功");
        }
        return ResponseData.error("删除失败");
    }

    @Override
    public ResponseData modifyMenu(MenuInfo menu) {
        boolean update = this.updateById(menu);
        if (update) {
            return ResponseData.success("修改成功");
        }
        return ResponseData.error("修改失败");
    }

    @Override
    public ResponseData moveMenu(Long id, Integer move) {
        MenuInfo menuInfo = this.getById(id);
        if (move == null) {
            return ResponseData.error("移动参数不能为空");
        }
        if (menuInfo == null) {
            return ResponseData.error("未找到要排序的菜单");
        }
        Integer oldSort = menuInfo.getMenuSort();
        Integer menuSort = menuInfo.getMenuSort();
        if (move == 1) {
            menuSort = menuSort - 1;
        } else {
            if (menuSort == 0) {
                return ResponseData.error("已经是最上层");
            }
            menuSort = menuSort + 1;
        }
        menuInfo.setMenuSort(menuSort);
        MenuInfo menuBySort = this.baseMapper.getMenuBySort(menuSort, menuInfo.getParentId());
        if (menuBySort == null) {
            if (menuSort == -1) {
                return ResponseData.error("已经是最上层");
            }
            return ResponseData.error("已经是最底层");
        }
        menuBySort.setMenuSort(oldSort);
        this.baseMapper.updateById(menuInfo);
        this.baseMapper.updateById(menuBySort);
        return ResponseData.success("操作成功");
    }
}

